//import { openViewChaptersModal,closeViewChaptersModal} from './chapter.js';
import { viewResources,previewResource,downloadResource,openAllVersionsModal} from './resource.js';
//import { openCoursePreviewModal, closeCoursePreviewModal } from './course.js';
window.viewResources = viewResources;
window.previewResource = previewResource;
window.downloadResource = downloadResource;
//window.closeAllVersionsModal = closeAllVersionsModal;
//window.closeViewResourcesModal = closeViewResourcesModal;
// 页面加载完成后显示已选课程
import { editProfile,logout,setupUserProfile} from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
window.onload = async function () {
    showSelectedCourses();
};
let filterDebounceTimer = null;
export async function showSelectedCourses() {
    try {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        if (!username) {
            throw new Error('URL中缺少username参数');
        }
        await setupUserProfile(username);
        const response = await fetch(`/get-selected-courses?username=${username}`);
        const courses = await response.json();

        const selectedCourseList = document.getElementById('selectedCourseList');
        selectedCourseList.innerHTML = '';

        if (courses.length === 0) {
            selectedCourseList.innerHTML = `
    <div class="empty-state">
        <div class="empty-icon">
            <i class="fas fa-book-open text-4xl text-gray-400"></i>
        </div>
        <h3 class="empty-title">暂无已选课程</h3>
        <p class="empty-description">您还没有选择任何课程，快去选课中心看看吧</p>
    </div>
`;
        }

        for (const course of courses) {
            const teacher_name_response = await fetch(`/user-info-by-id?userId=${course.teacher_user_id}`);
            const teacher_name_json = await teacher_name_response.json();
            const teacher_name = teacher_name_json.name;
        
            // 获取课程助教信息
            const tutorsResponse = await fetch(`/get-course-tutors?courseCode=${course.course_code}`);
            const tutors = await tutorsResponse.json();
            let tutorNamesDisplay = "暂无助教";
            if (tutors && tutors.length > 0) {
                tutorNamesDisplay = tutors.map(tutor => tutor.tutor_name).join(',');
            }
        
            const courseBox = document.createElement('div');
            courseBox.classList.add('course-box');
            
            const buttonHtml = `
            <div class="button-group">
                <button class="action-btn chapter-btn" onclick="openViewChaptersModal('${course.course_code}')">
                    <i class="fas fa-list-alt"></i>
                    <span>课程章节</span>
                </button>
                
                <button class="action-btn resource-btn" onclick="new_openViewResourcesModal('${course.course_code}')">
                    <i class="fas fa-folder-open"></i>
                    <span>学习资源</span>
                </button>
                
                <button class="action-btn preview-btn" onclick="openCoursePreviewModal('${course.course_code}')">
                    <i class="fas fa-play-circle"></i>
                    <span>课程预览</span>
                </button>
        
                <button class="action-btn drop-btn" onclick="dropCourse('${course.course_code}')">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>退选课程</span>
                </button>
            </div>
            `;
        
            courseBox.innerHTML = `
            <div class="course-header">
                <h3 class="course-title">
                    <i class="fas fa-book-open text-primary"></i>
                    <span class="text-gradient">${course.course_code}——${escapeHTML(course.course_name)}</span>
                </h3>
                <div class="course-meta">
                    <span class="meta-item">
                        <i class="fas fa-user-tie text-teacher"></i>
                        <span class="meta-text">${escapeHTML(teacher_name)}</span>
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-clock text-time"></i>
                        <span class="meta-text">${course.course_time}</span>
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-map-marker-alt text-location"></i>
                        <span class="meta-text">${course.place}</span>
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-user-graduate text-tutor"></i>
                        <span class="meta-text">课程助教：${escapeHTML(tutorNamesDisplay)}</span>
                    </span>
                </div>
            </div>
        
            <div class="course-details">
                <div class="detail-card">
                    <div class="detail-item">
                        <i class="fas fa-star text-credits"></i>
                        <span class="detail-label">课程学分</span>
                        <span class="detail-value">${course.credits}</span>
                    </div>
                    <div class="detail-item">
                        <i class="fas fa-hourglass-half text-period"></i>
                        <span class="detail-label">课程学时</span>
                        <span class="detail-value">${course.study_period}</span>
                    </div>
                    <div class="detail-item assessment-item">
                        <div class="assessment-icon">
                            <i class="fas fa-clipboard-check text-assessment"></i>
                        </div>
                        <div class="assessment-content">
                            <div class="detail-label">考核方式</div>
                            <div class="detail-value assessment-value">${escapeHTML(course.assessment_method)}</div>
                        </div>
                    </div>
                </div>
                
                <div class="course-description">
                    <p class="description-title">
                        <i class="fas fa-bullseye text-objective"></i> 
                        <span>教学目标</span>
                    </p>
                    <p class="description-content">${escapeHTML(course.teaching_objectives)}</p>
                </div>
                
                <div class="course-footer">
                    <p class="weeks-info">
                        <i class="fas fa-calendar-alt text-week"></i>
                        <span>上课周次：${course.teach_weeks}</span>
                    </p>
                    <p class="toggle-tip">
                        <i class="fas fa-hand-pointer text-toggle"></i>
                        <span>点击展开操作菜单</span>
                    </p>
                </div>
            </div>
        
            <div class="button-group" style="display:none">
                ${buttonHtml}
            </div>
            `;
        
            courseBox.addEventListener('click', () => {
                const buttons = courseBox.querySelector('.button-group');
                if (buttons.style.display === 'none') {
                    buttons.style.display = 'block';
                } else {
                    buttons.style.display = 'none';
                }
            });
        
            selectedCourseList.appendChild(courseBox);
        }

        document.getElementById('selectedCourses').style.display = 'block';
        document.getElementById('learnedMaterials').style.display = 'none';
    } catch (error) {
        console.error('获取已选课程信息失败:', error);
        alert('获取已选课程信息失败，请稍后重试');
    }
}

export async function showLearnedMaterials() {
    document.getElementById('selectedCourses').style.display = 'none';
    document.getElementById('learnedMaterials').style.display = 'block';
    await showLearnedResources();
}
window.showSelectedCourses = showSelectedCourses;
window.showLearnedMaterials = showLearnedMaterials;

export async function dropCourse(courseCode) {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const userResponse = await fetch(`/user-info?username=${username}`);
    const userData = await userResponse.json();
    const studentId = userData.user_id;

    const response = await fetch('/drop-course', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            student_id: studentId,
            course_code: courseCode
        })
    });
    const result = await response.json();
    alert(result.message);
    // 刷新课程列表
    await showSelectedCourses();
}

window.dropCourse = dropCourse;

// 获取用户已学资源
export async function getLearnedResources(userId) {
    try {
        const response = await fetch(`/get-learned-resources?userId=${userId}`);
        const resourceIds = await response.json();
        return resourceIds;
    } catch (error) {
        console.error('获取已学资源失败:', error);
        alert('获取已学资源失败，请稍后重试');
        return [];
    }
}

// 获取资源详细信息
export async function getResourceInfo(resourceId) {
    try {
        //console.log('获取资源信息:', resourceId);
        const response = await fetch(`/get-resource-info/${resourceId}`);
        const resource = await response.json();
        //console.log('资源信息:', resource);
        return resource;
    } catch (error) {
        console.error('获取资源信息失败:', error);
        return null;
    }
}

// 获取课程详细信息
export async function getCourseInfo(courseCode) {
    try {
        const response = await fetch(`/get-course/${courseCode}`);
        const course = await response.json();
        return course;
    } catch (error) {
        console.error('获取课程信息失败:', error);
        return null;
    }
}

// 展示已学资源
export async function showLearnedResources() {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const userResponse = await fetch(`/user-info?username=${username}`);
    const userData = await userResponse.json();
    const userId = userData.user_id;
    const resourceIds = await getLearnedResources(userId);
    const learnedResourceList = document.getElementById('learnedResourceList');
    learnedResourceList.innerHTML = '';

    if (resourceIds.length === 0) {
        learnedResourceList.innerHTML = `
            <div class="empty-state">
                <div class="empty-icon">
                    <i class="fas fa-file-alt text-4xl text-blue-400"></i>
                </div>
                <h3 class="empty-title">暂无已学资源</h3>
                <p class="empty-description">您还没有学习任何资源，快去课程中学习吧</p>
                <button onclick="showSelectedCourses()" class="action-btn select-course-btn">
                    <i class="fas fa-book mr-2"></i>查看课程
                </button>
            </div>
        `;
        return;
    }

    for (const resourceId of resourceIds) {
        const resource = await getResourceInfo(resourceId);
        if (resource) {
            const course = await getCourseInfo(resource.course_code);
            const resourceBox = document.createElement('div');
            resourceBox.classList.add('learned-resource-card'); // 添加卡片类名
            
            // 获取文件类型
            const fileName = resource.resource_content.split('\\').pop();
            const fileExtension = fileName.split('.').pop().toLowerCase();
            
            resourceBox.innerHTML = `
                <div class="resource-header">
                    <div class="resource-icon">
                        <i class="fas fa-file-${getFileIcon(fileExtension)}"></i>
                    </div>
                    <div class="resource-info">
                        <h3 class="resource-title">${fileName}</h3>
                        <div class="resource-meta">
                            <span><i class="fas fa-clock"></i> ${resource.create_time}</span>
                            <span><i class="fas fa-book"></i> ${course ? course.course_name : '未知课程'}</span>
                        </div>
                    </div>
                </div>
                <div class="resource-actions">
                    <button class="action-btn preview-btn" onclick="previewResource('${resourceId}')">
                        <i class="fas fa-eye"></i>
                        预览
                    </button>
                    <button class="action-btn download-btn" onclick="downloadResource('${resourceId}')">
                        <i class="fas fa-download"></i>
                        下载
                    </button>
                    <button class="action-btn unlearn-btn" onclick="markAsUnlearned('${resourceId}')">
                        <i class="fas fa-undo"></i>
                        标记未学
                    </button>
                </div>
            `;

            learnedResourceList.appendChild(resourceBox);
        }
    }
}

// 辅助函数：根据文件扩展名获取图标类
export function getFileIcon(extension) {
    const iconMap = {
        'pdf': 'pdf',
        'doc': 'word',
        'docx': 'word',
        'xls': 'excel',
        'xlsx': 'excel',
        'ppt': 'powerpoint',
        'pptx': 'powerpoint',
        'jpg': 'image',
        'jpeg': 'image',
        'png': 'image',
        'txt': 'alt',
        'zip': 'archive',
        'rar': 'archive'
    };
    return iconMap[extension] || 'alt';
}


// 标记资源为未学
export async function markAsUnlearned(resourceId) {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    const userResponse = await fetch(`/user-info?username=${username}`);
    const userData = await userResponse.json();
    const userId = userData.user_id;

    try {
        const response = await fetch('/mark-as-unlearned', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                user_id: userId,
                resource_id: resourceId
            })
        });

        const result = await response.json();
        alert(result.message);
        // 刷新已学资源列表
        await showLearnedMaterials();
    } catch (error) {
        console.error('标记资源为未学失败:', error);
        alert('标记资源为未学失败，请稍后重试');
    }
}

window.showLearnedResources = showLearnedResources;
window.markAsUnlearned = markAsUnlearned;

document.getElementById('goBackButton').addEventListener('click',async()=>{
    window.location.href = 'success.html' + window.location.search;
});

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='success.html'+window.location.search;
        });
    }
});

// 显示模态框
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.add('active');
    document.body.style.overflow = 'hidden';
}

// 关闭模态框
export function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.remove('active');
    document.body.style.overflow = '';
}

// 示例：查看章节模态框控制
export async function openViewChaptersModal(courseCode) {
    const response = await fetch(`/get-chapters?courseCode=${courseCode}`);
    const chapters = await response.json();
    const chapterList = document.getElementById('chapterList');
    chapterList.innerHTML = '';
    if (chapters.length === 0) {
        chapterList.innerHTML = '<p class="no-content-message">暂无章节</p>';
    }
    chapters.forEach(chapter => {
        const chapterBox = document.createElement('div');
        chapterBox.classList.add('course-box');
        chapterBox.innerHTML = `
<div class="chapter-container">
    <div class="chapter-header">
        <span class="chapter-badge">第${chapter.chapter_order + 1}章</span>
        <h3 class="chapter-title">${escapeHTML(chapter.chapter_title)}</h3>
    </div>
    
    <div class="chapter-content">
        <div class="content-header">
            <i class="fas fa-align-left content-icon"></i>
            <h4 class="content-title">章节内容</h4>
        </div>
        <div class="content-text">${escapeHTML(chapter.chapter_content)}</div>
    </div>
</div>
`;
        chapterList.appendChild(chapterBox);
    });
    openModal('viewChaptersModal');
}

export function closeViewChaptersModal() {
    closeModal('viewChaptersModal');
}

window.openViewChaptersModal = openViewChaptersModal;
window.closeViewChaptersModal = closeViewChaptersModal;

export async function openCoursePreviewModal(courseCode) {
    try {
        // 获取课程详细信息
        const courseResponse = await fetch(`/get-course/${courseCode}`);
        const course = await courseResponse.json();

        // 获取课程对应的章节信息
        const chaptersResponse = await fetch(`/get-chapters?courseCode=${courseCode}`);
        const chapters = await chaptersResponse.json();

        const coursePreviewInfo = document.getElementById('coursePreviewInfo');
        coursePreviewInfo.innerHTML = `
            <div class="course-preview-header">
                <h3 class="text-2xl font-bold text-gray-800 mb-2">
                    <i class="fas fa-book-open mr-2 text-blue-500"></i>
                    ${course.course_code} - ${escapeHTML(course.course_name)}
                </h3>
                <div class="course-meta grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                    <div class="meta-item flex items-center">
                        <i class="fas fa-user-tie mr-2 text-gray-600"></i>
                        <span><strong>教师:</strong> ${escapeHTML(course.teacher_name)}</span>
                    </div>
                    <div class="meta-item flex items-center">
                        <i class="fas fa-clipboard-check mr-2 text-gray-600"></i>
                        <span><strong>考核方式:</strong> ${escapeHTML(course.assessment_method)}</span>
                    </div>
                </div>
            </div>

            <div class="course-preview-content space-y-6">
                <div class="objective-section bg-blue-50 p-4 rounded-lg">
                    <h4 class="text-lg font-semibold text-blue-700 mb-2 flex items-center">
                        <i class="fas fa-bullseye mr-2"></i>教学目标
                    </h4>
                    <p class="text-gray-700 pl-6">${escapeHTML(course.teaching_objectives)}</p>
                </div>

                <div class="syllabus-section bg-gray-50 p-4 rounded-lg">
                    <h4 class="text-lg font-semibold text-gray-700 mb-2 flex items-center">
                        <i class="fas fa-map mr-2"></i>课程大纲
                    </h4>
                    <p class="text-gray-700 pl-6">${escapeHTML(course.syllabus)}</p>
                </div>

                <div class="chapters-section">
                    <h4 class="text-xl font-semibold text-gray-800 mb-4 border-b pb-2 flex items-center">
                        <i class="fas fa-list-ol mr-2"></i>课程章节
                    </h4>
                    ${chapters.length > 0 ? `
                        <ul class="space-y-3 chapter-list">
                            ${chapters.map(chapter => `
                                <li class="chapter-item bg-white p-3 rounded-lg shadow-sm hover:shadow-md transition-shadow">
                                    <div class="flex items-start">
                                        <span class="chapter-order bg-blue-100 text-blue-800 px-2 py-1 rounded-full text-sm font-medium mr-3">
                                            第${chapter.chapter_order + 1}章
                                        </span>
                                        <div>
                                            <h5 class="font-medium text-gray-800">${escapeHTML(chapter.chapter_title)}</h5>
                                            <p class="text-gray-600 mt-1">${escapeHTML(chapter.chapter_content)}</p>
                                        </div>
                                    </div>
                                </li>
                            `).join('')}
                        </ul>
                    ` : '<p class="text-gray-500 italic">暂无章节信息</p>'}
                </div>
            </div>
        `;

        openModal('coursePreviewModal');
    } catch (error) {
        console.error('获取课程信息失败:', error);
        alert('获取课程信息失败，请稍后重试');
    }
}

export function closeCoursePreviewModal() {
    closeModal('coursePreviewModal');
}

window.openCoursePreviewModal = openCoursePreviewModal;
window.closeCoursePreviewModal = closeCoursePreviewModal;

export async function new_openViewResourcesModal(courseCode){
    const chaptersResponse = await fetch(`/get-chapters?courseCode=${courseCode}`);
    const chapters = await chaptersResponse.json();

    // 检查是否有章节
    if (chapters.length === 0) {
        //console.log('该课程没有章节');
        alert('该课程目前没有章节，无法查看资源');
        return;
    }
    openModal('viewResourcesModal');
    await viewResources(courseCode);
}

function closeViewResourcesModal(){
    closeModal('viewResourcesModal');
}

window.new_openViewResourcesModal = new_openViewResourcesModal;
window.closeViewResourcesModal = closeViewResourcesModal;

/*async function openAllVersionsModal(resourceId) {
    console.log('Opening all versions modal for resource ID:', resourceId);
    try {
        const response = await fetch(`/get-resource-versions/${resourceId}`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const versions = await response.json();
        const versionList = document.getElementById('versionList');
        versionList.innerHTML = '';

        versions.forEach(version => {
            const listItem = document.createElement('div');
            listItem.classList.add('resource-box');

            const resourceName = document.createElement('p');
            // 去掉 uploads/ 前缀
            resourceName.textContent = version.resource_content.split('\\').pop();
            listItem.appendChild(resourceName);

            const createTime = document.createElement('p');
            // 显示资源的创建时间
            createTime.textContent = `创建时间: ${version.create_time}`; 
            listItem.appendChild(createTime);

            const previewButton = document.createElement('button');
            previewButton.textContent = '在线预览';
            previewButton.addEventListener('click', () => previewResource(version.resource_id));
            listItem.appendChild(previewButton);

            const downloadButton = document.createElement('button');
            downloadButton.textContent = '下载到本地';
            downloadButton.addEventListener('click', () => downloadResource(version.resource_id));
            listItem.appendChild(downloadButton);

            // 增加按钮间距
            previewButton.style.marginRight = '10px';

            versionList.appendChild(listItem);
        });
        openModal('allVersionsModal');
    } catch (error) {
        console.error('Error getting resource versions:', error);
        alert('获取资源版本失败，请稍后重试');
    }
}*/

export function closeAllVersionsModal() {
    closeModal('allVersionsModal');
    //document.getElementById('allVersionsModal').style.display = 'none';
}

window.openAllVersionsModal = openAllVersionsModal;
window.closeAllVersionsModal = closeAllVersionsModal;

// 在resource.js中添加以下代码
document.addEventListener('DOMContentLoaded', () => {
    // 从URL获取courseCode
    const urlParams = new URLSearchParams(window.location.search);
    const courseCode = urlParams.get('courseCode');
    
    if (courseCode && typeof courseCode === 'string') {
        // 使用setupResourceFilters设置正确的监听器
        setupResourceFilters(courseCode);
    } else {
        //console.error('无效的courseCode参数:', courseCode);
    }
});

function escapeHTML(str) {
    if (typeof str !== 'string') return str;
    if (!str) return '';
    return str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}